package servlet;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

@WebServlet(name = "Servlet2", value = "/watch")
public class HomeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String filename = request.getParameter("filename");
        String type = request.getParameter("type");

        String mimeType = getServletContext().getMimeType(filename);

        response.setContentType(mimeType);
        if (type != null || "download".equals(type)) {
            response.setHeader("content-disposition",
                    "attachment;filename=" + URLEncoder.encode(filename, "utf-8"));
        }

        String realPath = getServletContext().getRealPath("file/" + filename);
        FileInputStream fileInputStream = new FileInputStream(realPath);
        byte bt[] = new byte[1024];
        int len = 0;
        while ((len = fileInputStream.read(bt)) != -1) {
            response.getOutputStream().write(bt, 0, len);
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
